// pages/prize/prize.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img:"../../images/gobg.png",
    wechat:"../../images/wechat.png",
    quan:"../../images/quan.png",
    invi_code:"",
    inputValue:"",
    maskHidden: false,
    name:"",
    touxiang:"",
    eq_img:'',
    userInfo:[]
  },
  //获取输入框的值
  bindKeyInput:function(e){
    this.setData({
      inputValue: e.detail.value
    })
  },
  //点击提交按钮
  btnclick:function(){
    let _this = this;
    var invi_code = this.data.inputValue;
    if(invi_code.length != 6){
      wx.showToast({
        title: '邀请码有误',
        icon: 'none',
        duration: 2000
      })
    }else{
      app._post('api/member/lock_parent', {invi_code:invi_code}, function(result) {
        if(result.code == 200){
          var icon = 'success';
          _this.get_user_info();
        }else{
          var icon = 'none';
        }
        wx.showToast({
          title: result.msg,
          icon: 'none',
          duration: 2000
        })

      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var that = this;
    wx.getSetting({
      success (res){
        console.log(res);
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
              success: res => {
                console.log(res.userInfo,"huoqudao le ")
                that.setData({
                  name: res.userInfo.nickName,
                })
                wx.downloadFile({
                  url: res.userInfo.avatarUrl, //仅为示例，并非真实的资源
                  success: function (res) {
                    console.log(res);
                    // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                    if (res.statusCode === 200) {
                      console.log(res, "reererererer")
                      that.setData({
                        touxiang: res.tempFilePath
                      })
                      console.log(that.data.touxiang)
                    }
                  },
                   fail:function(err){
                      console.log(err)             
                  }
                })
              }
            })
        }
      },
      fail(error){
        console.log(error)
      }
    })
    
    that.get_user_info();
  },

  get_user_info:function(){
    let _this = this;
    app._post('api/member/getUserInfo', {}, function(result) {
      if(result.code == 200){
        _this.setData({
          userInfo:result.data,
          invi_code:result.data.invi_code
        })
        //获取个人二维码
        _this.get_eq();
      }else{
        wx.navigateTo({
          url: '/pages/auth/auth'
        })
      }
    });
  },

  //获取个人二维码
  get_eq:function(){
    let _this = this;
    app._get('api/wxlogic/get_eq', {
      page:'pages/index/index',
      scene:'inviteCode='+_this.data.userInfo.member_id
    }, function(result) {
      console.log(result);
      const fsm = wx.getFileSystemManager();
      const FILE_BASE_NAME = 'tmp_base64src';

      function base64src(base64data) {
        return new Promise((resolve, reject) => {
          const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
          if (!format) {
            reject(new Error('ERROR_BASE64SRC_PARSE'));
          }
          const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
          const buffer = wx.base64ToArrayBuffer(bodyData);
          fsm.writeFile({
            filePath,
            data: buffer,
            encoding: 'binary',
            success() {
              _this.setData({eq_img:filePath});
              console.log(_this.data.eq_img)
              resolve(filePath);
            },
            fail() {
              reject(new Error('ERROR_BASE64SRC_WRITE'));
            },
          });
        });
      };
      base64src(result.data.img_url);
    });
  },

  //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg: function () {
    var that = this,
     eq_img = that.data.eq_img;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#ffe200")
    context.fillRect(0, 0, 375, 620)
    var path = "../../images/gobg.png";
    //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    //不知道是什么原因，手机环境能正常显示
    context.drawImage(path, 0, 0, 375, 183);
    var path1 = that.data.touxiang;
    //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    var path3 = "../../images/heise.png";
    var path4 = "../../images/wenziBg.png";
    var path5 = "../../images/wenxin.png";

    var name = that.data.name;
    //绘制邀请菊花码
    context.drawImage(eq_img, 255, 480, 80, 80);
    //绘制名字
    context.setFontSize(24);
    context.setFillStyle('#333333');
    context.setTextAlign('center');
    context.fillText(name, 185, 340);
    context.stroke();
    //绘制一起吃面标语
    context.setFontSize(14);
    context.setFillStyle('#333333');
    context.setTextAlign('center');
    context.fillText("邀请您一起去记账", 185, 370);
    context.stroke();
    //绘制验证码背景
    context.drawImage(path3, 48, 390, 280, 84);
    //绘制code码
    context.setFontSize(40);
    context.setFillStyle('#ffe200');
    context.setTextAlign('center');
    context.fillText(that.data.invi_code, 185, 435);
    context.stroke();
    //绘制左下角文字背景图
    context.drawImage(path4, 25, 500, 184, 82);
    context.setFontSize(12);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.fillText("进入小程序输入朋友的邀请", 35, 520);
    context.stroke();
    context.setFontSize(12);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.fillText("码，朋友和你各自获得平台", 35, 540);
    context.stroke();
    context.setFontSize(12);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.fillText("10积分~", 35, 560);
    context.stroke();
    //绘制右下角扫码提示语
    context.drawImage(path5, 248, 570, 90, 25);
    //绘制头像
    context.arc(186, 246, 50, 0, 2 * Math.PI) //画出圆
    context.strokeStyle = "#ffe200";
    context.clip(); //裁剪上面的圆形
    context.drawImage(path1, 136, 196, 100, 100); 
    
    context.draw();


    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden:true
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);
  },
  //点击保存到相册
  baocun:function(){
    var that = this;
    console.log('保存')
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                maskHidden: false
              })
            }
          },fail:function(res){
            console.log(11111)
          }
        })
      }
    })
  },
  
  //点击生成
  formSubmit: function (e) {
    var that = this,
    touxiang = that.data.touxiang;

    that.setData({
      maskHidden: false
    });
    wx.showToast({
      title: '装逼中...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function () {
        console.log(touxiang)
        if(touxiang!=''){
            wx.hideToast()
            that.createNewImg();
            that.setData({
                maskHidden: true
            });
        }      
    }, 1500)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },


  //隐藏悬浮层
  close_inv:function(){
    this.setData({
        maskHidden: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
})